"""FastAPI主应用入口"""
from fastapi import FastAPI, Request, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from app.core.config import settings
from app.core.database import init_db, close_db
from app.api.routes import assessment, training, progress, analysis, mock_exam, daily_learning, legal_thinking, user_status, scraper, debate
import traceback


app = FastAPI(
    title=settings.APP_NAME,
    version=settings.APP_VERSION,
    description="基于Human-as-a-Model法律思维训练系统的AI法考备考平台",
    docs_url="/docs",
    redoc_url="/redoc",
)

# CORS配置
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:3000", "http://127.0.0.1:3000"],  # 允许的前端来源
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"],
    allow_headers=["*"],
    expose_headers=["*"],
)


# 全局异常处理器
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    """全局异常处理器"""
    import traceback
    error_trace = traceback.format_exc()
    print(f"未处理的异常: {exc}")
    print(error_trace)
    return JSONResponse(
        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
        content={
            "error": "内部服务器错误",
            "detail": str(exc),
            "path": str(request.url)
        },
        headers={
            "Access-Control-Allow-Origin": "http://localhost:3000",
            "Access-Control-Allow-Credentials": "true",
        }
    )


@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    """请求验证异常处理器"""
    return JSONResponse(
        status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
        content={
            "error": "请求参数验证失败",
            "detail": exc.errors()
        },
        headers={
            "Access-Control-Allow-Origin": "http://localhost:3000",
            "Access-Control-Allow-Credentials": "true",
        }
    )

# 注册路由
app.include_router(assessment.router, prefix=settings.API_V1_PREFIX, tags=["评估诊断"])
app.include_router(training.router, prefix=settings.API_V1_PREFIX, tags=["训练系统"])
app.include_router(progress.router, prefix=settings.API_V1_PREFIX, tags=["进度追踪"])
app.include_router(analysis.router, prefix=settings.API_V1_PREFIX, tags=["正确率分析"])
app.include_router(mock_exam.router, prefix=settings.API_V1_PREFIX, tags=["模拟测试"])
app.include_router(daily_learning.router, prefix=settings.API_V1_PREFIX, tags=["每日学习"])
app.include_router(legal_thinking.router, prefix=settings.API_V1_PREFIX, tags=["法律思维训练"])
app.include_router(debate.router, prefix=settings.API_V1_PREFIX, tags=["辩论训练"])
app.include_router(user_status.router, prefix=settings.API_V1_PREFIX, tags=["用户状态"])
app.include_router(scraper.router, prefix=settings.API_V1_PREFIX, tags=["爬虫管理"])


@app.on_event("startup")
async def startup_event():
    """应用启动事件（快速启动，不阻塞）"""
    # 数据库初始化改为延迟加载，不阻塞服务启动
    # init_db() 会在首次使用时自动初始化
    pass


@app.on_event("shutdown")
async def shutdown_event():
    """应用关闭事件"""
    close_db()


@app.get("/")
async def root():
    """根路径"""
    return {
        "message": "AI法考备考软件API",
        "version": settings.APP_VERSION,
        "docs": "/docs"
    }


@app.get("/health")
async def health_check():
    """健康检查"""
    return {"status": "healthy"}

